<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商家管理后台</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            padding-top: 56px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }
        .main-content {
            margin-left: 250px;
            padding-top: 56px;
        }
        .nav-link.active {
            background-color: #0d6efd;
            color: white !important;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
        }
        .form-section {
            display: none;
        }
        .form-section.active {
            display: block;
        }
        .navbar-brand {
            font-weight: bold;
        }
        .toast-container {
            position: fixed;
            top: 70px;
            right: 20px;
            z-index: 9999;
        }
        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f8f9fa;
        }
        .login-card {
            width: 100%;
            max-width: 400px;
            padding: 20px;
        }
        .product-image {
            max-width: 100px;
            max-height: 100px;
        }
        .stat-card {
            text-align: center;
            padding: 20px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border: 1px solid rgba(0, 0, 0, 0.125);
            border-radius: 0.5rem;
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            margin: 10px 0;
        }
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.8;
        }
        .navbar-brand {
            font-weight: bold;
            display: flex;
            align-items: center;
        }
        .navbar-brand i {
            margin-right: 10px;
        }
        .action-buttons .btn {
            margin-right: 5px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
<!-- 登录界面 -->
<div id="loginPage" class="login-container">
    <div class="card login-card">
        <div class="card-body">
            <h3 class="card-title text-center mb-4">商家管理后台登录</h3>
            <form id="loginForm">
                <div class="mb-3">
                    <label for="username" class="form-label">用户名</label>
                    <input type="text" class="form-control" id="username" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">密码</label>
                    <input type="password" class="form-control" id="password" required>
                </div>
                <div class="d-grid">
                    <button type="submit" class="btn btn-primary">登录</button>
                </div>
            </form>
            <div class="text-center mt-3">
                <button id="showRegisterBtn" class="btn btn-link">没有账户？点击注册</button>
            </div>
        </div>
    </div>
</div>

<!-- 注册界面 -->
<div id="registerPage" class="login-container" style="display: none;">
    <div class="card login-card">
        <div class="card-body">
            <h3 class="card-title text-center mb-4">管理员注册</h3>
            <form id="registerForm">
                <div class="mb-3">
                    <label for="regUsername" class="form-label">用户名</label>
                    <input type="text" class="form-control" id="regUsername" required>
                </div>
                <div class="mb-3">
                    <label for="regPassword" class="form-label">密码</label>
                    <input type="password" class="form-control" id="regPassword" required>
                </div>
                <div class="d-grid">
                    <button type="submit" class="btn btn-success">注册</button>
                </div>
            </form>
            <div class="text-center mt-3">
                <button id="showLoginBtn" class="btn btn-link">已有账户？返回登录</button>
            </div>
        </div>
    </div>
</div>

<!-- 主界面 -->
<div id="mainApp" style="display: none;">
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="bi bi-shop"></i> 商家管理后台
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="logoutBtn">
                            <i class="bi bi-box-arrow-right"></i> 登出 (<span id="currentUser"></span>)
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#" data-target="dashboard">
                                <i class="fas fa-tachometer-alt"></i> 控制面板
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-target="products">
                                <i class="fas fa-box"></i> 商品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-target="coupons">
                                <i class="fas fa-ticket-alt"></i> 优惠券管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-target="statistics">
                                <i class="fas fa-chart-bar"></i> 销售统计
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主要内容区域 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <!-- Toast 提示框 -->
                <div class="toast-container">
                    <div id="toast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="d-flex">
                            <div class="toast-body" id="toastMessage"></div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                    </div>
                </div>

                <!-- 控制面板 -->
                <div class="form-section active" id="dashboard">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2"><i class="fas fa-tachometer-alt me-2"></i>控制面板</h1>
                    </div>

                    <div class="row">
                        <div class="col-md-3 mb-4">
                            <div class="card stat-card border-primary">
                                <div class="card-body text-center">
                                    <div class="stat-icon text-primary mb-2">
                                        <i class="fas fa-boxes"></i>
                                    </div>
                                    <div class="stat-number text-primary" id="totalProducts">0</div>
                                    <h5 class="card-title">商品总数</h5>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3 mb-4">
                            <div class="card stat-card border-success">
                                <div class="card-body text-center">
                                    <div class="stat-icon text-success mb-2">
                                        <i class="fas fa-ticket-alt"></i>
                                    </div>
                                    <div class="stat-number text-success" id="totalCoupons">0</div>
                                    <h5 class="card-title">优惠券</h5>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3 mb-4">
                            <div class="card stat-card border-info">
                                <div class="card-body text-center">
                                    <div class="stat-icon text-info mb-2">
                                        <i class="fas fa-user-shield"></i>
                                    </div>
                                    <div class="stat-number text-info" id="totalAdmins">0</div>
                                    <h5 class="card-title">管理员</h5>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3 mb-4">
                            <div class="card stat-card border-warning">
                                <div class="card-body text-center">
                                    <div class="stat-icon text-warning mb-2">
                                        <i class="fas fa-chart-line"></i>
                                    </div>
                                    <div class="stat-number text-warning" id="totalSales">0</div>
                                    <h5 class="card-title">总销量</h5>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">最近操作</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="list-group" id="recentActivities">
                                        <li class="list-group-item">暂无操作记录</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 商品管理 -->
                <div class="form-section" id="products">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2"><i class="fas fa-box me-2"></i>商品管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button class="btn btn-sm btn-outline-secondary me-2" id="refreshProducts">
                                <i class="bi bi-arrow-repeat"></i> 刷新
                            </button>
                            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal">
                                <i class="bi bi-plus-circle"></i> 添加商品
                            </button>
                        </div>
                    </div>

                    <!-- 商品筛选 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="searchProductName" class="form-label">商品名称</label>
                                    <input type="text" class="form-control" id="searchProductName" placeholder="搜索商品名称">
                                </div>
                                <div class="col-md-3">
                                    <label for="searchProductCategory" class="form-label">分类</label>
                                    <input type="text" class="form-control" id="searchProductCategory" placeholder="搜索分类">
                                </div>
                                <div class="col-md-3">
                                    <label for="searchProductStatus" class="form-label">状态</label>
                                    <select class="form-select" id="searchProductStatus">
                                        <option value="">全部</option>
                                        <option value="on">上架</option>
                                        <option value="off">下架</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button class="btn btn-primary w-100" id="searchProductBtn">
                                        <i class="bi bi-search"></i> 搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 商品列表 -->
                    <div class="card shadow-sm">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>商品名称</th>
                                        <th>价格</th>
                                        <th>分类</th>
                                        <th>状态</th>
                                        <th>销量</th>
                                        <th style="width: 250px;">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="productsTableBody">
                                    <!-- 商品数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 分页 -->
                    <nav aria-label="商品分页">
                        <ul class="pagination justify-content-center" id="productPagination">
                            <!-- 分页控件将通过JavaScript动态加载 -->
                        </ul>
                    </nav>
                </div>

                <!-- 优惠券管理 -->
                <div class="form-section" id="coupons">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2"><i class="fas fa-ticket-alt me-2"></i>优惠券管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addCouponModal">
                                <i class="bi bi-plus-circle"></i> 添加优惠券
                            </button>
                        </div>
                    </div>

                    <!-- 优惠券列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                            <tr>
                                <th>折扣率</th>
                                <th>优惠金额</th>
                                <th>最低消费</th>
                                <th>数量</th>
                                <th>过期时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="couponsTableBody">
                            <!-- 优惠券数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 销售统计 -->
                <div class="form-section" id="statistics">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2"><i class="fas fa-chart-bar me-2"></i>销售统计</h1>
                    </div>

                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-5">
                                    <label for="statStartDate" class="form-label">开始时间</label>
                                    <input type="date" class="form-control" id="statStartDate">
                                </div>
                                <div class="col-md-5">
                                    <label for="statEndDate" class="form-label">结束时间</label>
                                    <input type="date" class="form-control" id="statEndDate">
                                </div>
                                <div class="col-md-2 d-flex align-items-end">
                                    <button class="btn btn-primary w-100" id="generateStatBtn">
                                        <i class="bi bi-bar-chart"></i> 生成统计
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">销售数据</h5>
                                </div>
                                <div class="card-body">
                                    <div id="statResult">
                                        <p class="text-center text-muted">请选择时间范围并生成统计数据</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
</div>

<!-- 添加商品模态框 -->
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addProductModalLabel">添加新商品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addProductForm">
                    <div class="mb-3">
                        <label for="productName" class="form-label">商品名称</label>
                        <input type="text" class="form-control" id="productName" required>
                    </div>
                    <div class="mb-3">
                        <label for="productPrice" class="form-label">价格</label>
                        <input type="number" step="0.01" class="form-control" id="productPrice" required>
                    </div>
                    <div class="mb-3">
                        <label for="productCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="productCategory" required>
                    </div>
                    <div class="mb-3">
                        <label for="productDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="productDescription" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="productDetail" class="form-label">详细信息</label>
                        <textarea class="form-control" id="productDetail" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="productStatus" class="form-label">状态</label>
                        <select class="form-select" id="productStatus">
                            <option value="on">上架</option>
                            <option value="off">下架</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="productSales" class="form-label">初始销量</label>
                        <input type="number" class="form-control" id="productSales" value="0">
                    </div>
                    <div class="mb-3">
                        <label for="productRemark" class="form-label">备注</label>
                        <input type="text" class="form-control" id="productRemark">
                    </div>
                    <div class="mb-3">
                        <label for="productImages" class="form-label">商品图片</label>
                        <input type="file" class="form-control" id="productImages" multiple accept="image/*">
                    </div>
                    <div class="mb-3">
                        <label for="productVideos" class="form-label">商品视频</label>
                        <input type="file" class="form-control" id="productVideos" multiple accept="video/*">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveProductBtn">保存商品</button>
            </div>
        </div>
    </div>
</div>

<!-- 更新销量模态框 -->
<div class="modal fade" id="updateSalesModal" tabindex="-1" aria-labelledby="updateSalesModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateSalesModalLabel">更新商品销量</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="updateSalesForm">
                    <input type="hidden" id="updateSalesCreateTime">
                    <div class="mb-3">
                        <label for="newSales" class="form-label">新销量</label>
                        <input type="number" class="form-control" id="newSales" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="updateSalesBtn">更新销量</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加图片模态框 -->
<div class="modal fade" id="addImageModal" tabindex="-1" aria-labelledby="addImageModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addImageModalLabel">添加商品图片</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addImageForm">
                    <input type="hidden" id="addImageCreateTime">
                    <div class="mb-3">
                        <label for="newImage" class="form-label">选择图片</label>
                        <input type="file" class="form-control" id="newImage" accept="image/*" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="addImageButton">添加图片</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加视频模态框 -->
<div class="modal fade" id="addVideoModal" tabindex="-1" aria-labelledby="addVideoModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addVideoModalLabel">添加商品视频</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addVideoForm">
                    <input type="hidden" id="addVideoCreateTime">
                    <div class="mb-3">
                        <label for="newVideo" class="form-label">选择视频</label>
                        <input type="file" class="form-control" id="newVideo" accept="video/*" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="addVideoButton">添加视频</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加优惠券模态框 -->
<div class="modal fade" id="addCouponModal" tabindex="-1" aria-labelledby="addCouponModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCouponModalLabel">添加优惠券</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addCouponForm">
                    <div class="mb-3">
                        <label for="couponDiscount" class="form-label">折扣率 (0-1之间)</label>
                        <input type="number" step="0.01" min="0" max="1" class="form-control" id="couponDiscount" placeholder="例如: 0.9 表示9折">
                        <div class="form-text">折扣率和优惠金额只能填写一个，另一个必须为空</div>
                    </div>
                    <div class="mb-3">
                        <label for="couponReprice" class="form-label">优惠金额</label>
                        <input type="number" step="0.01" min="0" class="form-control" id="couponReprice" placeholder="例如: 10 表示减10元">
                        <div class="form-text">折扣率和优惠金额只能填写一个，另一个必须为空</div>
                    </div>
                    <div class="mb-3">
                        <label for="couponMin" class="form-label">最低消费金额</label>
                        <input type="number" step="0.01" min="0" class="form-control" id="couponMin" placeholder="例如: 100 表示满100可用">
                    </div>
                    <div class="mb-3">
                        <label for="couponQuantity" class="form-label">数量</label>
                        <input type="number" min="1" class="form-control" id="couponQuantity" placeholder="例如: 100">
                    </div>
                    <div class="mb-3">
                        <label for="couponExpireTime" class="form-label">过期时间</label>
                        <input type="date" class="form-control" id="couponExpireTime">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveCouponBtn">保存优惠券</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个商品吗？此操作不可撤销。</p>
                <input type="hidden" id="deleteProductCreateTime">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<!-- Font Awesome JS is included in the CSS version, so we don't need a separate JS file -->
<script>
    // 全局变量
    let currentToken = localStorage.getItem('adminToken') || '';
    let currentUser = localStorage.getItem('currentUser') || '';
    let currentPage = 1;
    let pageSize = 10;

    // 确保Bootstrap对象已完全加载
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化事件监听器
        initEventListeners();

        // 检查是否已登录
        checkLoginStatus();
    });

    // 检查登录状态
    function checkLoginStatus() {
        if (currentToken && currentUser) {
            showMainApp();
            loadDashboardData();
        } else {
            showLoginPage();
        }
    }

    // 显示登录页面
    function showLoginPage() {
        document.getElementById('loginPage').style.display = 'flex';
        document.getElementById('registerPage').style.display = 'none';
        document.getElementById('mainApp').style.display = 'none';
    }

    // 显示主应用
    function showMainApp() {
        document.getElementById('loginPage').style.display = 'none';
        document.getElementById('registerPage').style.display = 'none';
        document.getElementById('mainApp').style.display = 'block';
        document.getElementById('currentUser').textContent = currentUser;

        // 初始化导航切换
        initNavigation();
    }

    // 显示注册页面
    function showRegisterPage() {
        document.getElementById('loginPage').style.display = 'none';
        document.getElementById('registerPage').style.display = 'flex';
        document.getElementById('mainApp').style.display = 'none';
    }

    // 初始化事件监听器
    function initEventListeners() {
        // 登录表单提交
        document.getElementById('loginForm').addEventListener('submit', handleLogin);

        // 注册表单提交
        document.getElementById('registerForm').addEventListener('submit', handleRegister);

        // 显示注册按钮
        document.getElementById('showRegisterBtn').addEventListener('click', showRegisterPage);

        // 显示登录按钮
        document.getElementById('showLoginBtn').addEventListener('click', showLoginPage);

        // 登出按钮
        document.getElementById('logoutBtn').addEventListener('click', handleLogout);

        // 保存商品按钮
        document.getElementById('saveProductBtn').addEventListener('click', handleAddProduct);

        // 更新销量按钮
        document.getElementById('updateSalesBtn').addEventListener('click', handleUpdateSales);

        // 添加图片按钮
        document.getElementById('addImageButton').addEventListener('click', handleAddImage);

        // 添加视频按钮
        document.getElementById('addVideoButton').addEventListener('click', handleAddVideo);

        // 刷新商品列表
        document.getElementById('refreshProducts').addEventListener('click', function() {
            loadProducts(currentPage);
        });

        // 搜索商品
        document.getElementById('searchProductBtn').addEventListener('click', function() {
            loadProducts(1);
        });

        // 生成统计
        document.getElementById('generateStatBtn').addEventListener('click', generateStatistics);

        // 确认删除按钮
        document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteProduct);

        // 保存优惠券按钮
        document.getElementById('saveCouponBtn').addEventListener('click', handleAddCoupon);
    }

    // 初始化导航切换
    function initNavigation() {
        const navLinks = document.querySelectorAll('.nav-link[data-target]');
        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const target = this.getAttribute('data-target');

                // 更新活动链接
                document.querySelectorAll('.nav-link').forEach(nav => nav.classList.remove('active'));
                this.classList.add('active');

                // 显示对应的内容区域
                document.querySelectorAll('.form-section').forEach(section => {
                    section.classList.remove('active');
                });
                document.getElementById(target).classList.add('active');

                // 根据不同的目标加载数据
                switch(target) {
                    case 'dashboard':
                        loadDashboardData();
                        break;
                    case 'products':
                        loadProducts(1);
                        break;
                    case 'coupons':
                        loadCoupons();
                        break;
                }
            });
        });
    }

    // 显示提示信息
    function showToast(message, type = 'success') {
        const toastEl = document.getElementById('toast');
        const toastMessageEl = document.getElementById('toastMessage');

        toastMessageEl.textContent = message;
        toastMessageEl.className = 'toast-body text-white';
        toastMessageEl.classList.add('bg-' + type);

        const toast = new bootstrap.Toast(toastEl);
        toast.show();
    }

    // 登录处理
    function handleLogin(e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        fetch('http://localhost:80/admin/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user: username,
                password: password
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.token) {
                    currentToken = data.token;
                    currentUser = data.user;
                    localStorage.setItem('adminToken', currentToken);
                    localStorage.setItem('currentUser', currentUser);
                    showToast('登录成功！');
                    showMainApp();
                    loadDashboardData();
                } else {
                    showToast('登录失败：' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('登录过程中发生错误', 'danger');
            });
    }

    // 注册处理
    function handleRegister(e) {
        e.preventDefault();

        const username = document.getElementById('regUsername').value;
        const password = document.getElementById('regPassword').value;

        fetch('http://localhost:80/admin/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user: username,
                password: password
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('注册成功！请登录');
                    showLoginPage();
                } else {
                    showToast('注册失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('注册过程中发生错误', 'danger');
            });
    }

    // 登出处理
    function handleLogout() {
        currentToken = '';
        currentUser = '';
        localStorage.removeItem('adminToken');
        localStorage.removeItem('currentUser');
        showToast('已登出');
        showLoginPage();
    }

    // 加载仪表板数据
    function loadDashboardData() {
        // 从API获取真实数据
        fetch('http://localhost:80/admin/product/count', {
            method: 'GET',
            headers: {
                'Authorization': currentToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                document.getElementById('totalProducts').textContent = data.result || 0;
            } else {
                showToast('获取商品总数失败：' + data.message, 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('获取商品总数时发生错误', 'danger');
        });
        
        // 其他统计数据可以类似获取
        document.getElementById('totalCoupons').textContent = '0';
        document.getElementById('totalAdmins').textContent = '0';
        document.getElementById('totalSales').textContent = '0';
    }

    // 加载商品列表
    function loadProducts(page) {
        currentPage = page;
        const name = document.getElementById('searchProductName').value;
        const category = document.getElementById('searchProductCategory').value;
        const status = document.getElementById('searchProductStatus').value;

        // 构建查询参数
        let url = `http://localhost:80/public/product/get/page?page=${page-1}&size=${pageSize}`;
        if (name) url += `&name=${encodeURIComponent(name)}`;
        if (category) url += `&category=${encodeURIComponent(category)}`;
        if (status) url += `&status=${encodeURIComponent(status)}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    renderProducts(data.data);
                    renderPagination(); // 渲染分页控件
                } else {
                    showToast('加载商品失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('加载商品时发生错误', 'danger');
            });
    }

    // 渲染商品列表
    function renderProducts(products) {
        const tbody = document.getElementById('productsTableBody');
        tbody.innerHTML = '';

        if (!products || products.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="6" class="text-center">暂无商品数据</td>';
            tbody.appendChild(row);
            return;
        }

        products.forEach(product => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${product.name || ''}</td>
                    <td>¥${product.price || 0}</td>
                `;

            // 根据是否有category、status字段进行渲染
            if (product.category !== undefined) {
                row.innerHTML += `<td>${product.category || ''}</td>`;
            } else {
                row.innerHTML += '<td>未分类</td>';
            }

            if (product.status !== undefined) {
                row.innerHTML += `<td>${product.status === 'on' ? '上架' : '下架'}</td>`;
            } else {
                row.innerHTML += '<td>未知</td>';
            }

            row.innerHTML += `
                    <td>${product.sales || 0}</td>
                    <td class="action-buttons">
                        <div class="btn-group btn-group-sm" role="group">
                            <button class="btn btn-outline-primary" onclick="showUpdateSalesModal('${product.createTime}', ${product.sales})" title="更新销量">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-outline-warning" onclick="showAddImageModal('${product.createTime}')" title="添加图片">
                                <i class="bi bi-image"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showAddVideoModal('${product.createTime}')" title="添加视频">
                                <i class="bi bi-camera-video"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="showDeleteConfirmModal('${product.createTime}')" title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        // 首先获取产品总数以计算总页数
        fetch('http://localhost:80/admin/product/count', {
            method: 'GET',
            headers: {
                'Authorization': currentToken
            }
        })
        .then(response => response.json())
        .then(countData => {
            if (countData.code === 200) {
                const totalCount = countData.result || 0;
                const totalPages = Math.ceil(totalCount / pageSize);
                
                const pagination = document.getElementById('productPagination');
                pagination.innerHTML = '';

                // 上一页按钮
                const prevItem = document.createElement('li');
                prevItem.className = 'page-item ' + (currentPage <= 1 ? 'disabled' : '');
                prevItem.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${currentPage-1})">«</a>`;
                pagination.appendChild(prevItem);

                // 页码按钮 (显示当前页前后各3页)
                const startPage = Math.max(1, currentPage - 3);
                const endPage = Math.min(startPage + 6, totalPages, currentPage + 3);

                for (let i = startPage; i <= endPage; i++) {
                    const pageItem = document.createElement('li');
                    pageItem.className = 'page-item ' + (i === currentPage ? 'active' : '');
                    pageItem.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${i})">${i}</a>`;
                    pagination.appendChild(pageItem);
                }

                // 下一页按钮
                const nextItem = document.createElement('li');
                nextItem.className = 'page-item ' + (currentPage >= totalPages || totalPages === 0 ? 'disabled' : '');
                nextItem.innerHTML = `<a class="page-link" href="#" onclick="loadProducts(${currentPage+1})">»</a>`;
                pagination.appendChild(nextItem);
            } else {
                showToast('获取商品总数失败：' + countData.message, 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('获取商品总数时发生错误', 'danger');
        });
    }

    // 加载优惠券列表
    function loadCoupons() {
        fetch('http://localhost:80/admin/coupon/listAll', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': currentToken
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 根据返回的数据结构选择正确的字段
                    const coupons = data.data || data.result || [];
                    renderCoupons(coupons);
                } else {
                    showToast('加载优惠券失败：' + data.message, 'danger');
                    const tbody = document.getElementById('couponsTableBody');
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无优惠券数据</td></tr>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('加载优惠券时发生错误', 'danger');
                const tbody = document.getElementById('couponsTableBody');
                tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无优惠券数据</td></tr>';
            });
    }

    // 渲染优惠券列表
    function renderCoupons(coupons) {
        const tbody = document.getElementById('couponsTableBody');
        tbody.innerHTML = '';

        if (!coupons || coupons.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无优惠券数据</td></tr>';
            return;
        }

        coupons.forEach(coupon => {
            // 解析已分配的用户数量
            let assignedCount = 0;
            if (coupon.name) {
                try {
                    const assignedUsers = JSON.parse(coupon.name);
                    if (Array.isArray(assignedUsers)) {
                        assignedCount = assignedUsers.length;
                    }
                } catch (e) {
                    // 如果解析失败，保持assignedCount为0
                }
            }

            // 计算剩余数量
            const remainingCount = coupon.quantity - assignedCount;

            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${coupon.discount || 0}</td>
                    <td>¥${coupon.reprice || 0}</td>
                    <td>¥${coupon.min || 0}</td>
                    <td>${remainingCount} / ${coupon.quantity || 0}</td>
                    <td>${new Date(coupon.expireTime).toLocaleDateString() || ''}</td>
                    <td>
                        <button class="btn btn-sm btn-danger">删除</button>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 添加商品处理
    function handleAddProduct() {
        const formData = new FormData();

        // 创建商品信息对象
        const productInfo = {
            name: document.getElementById('productName').value,
            price: document.getElementById('productPrice').value,
            category: document.getElementById('productCategory').value,
            description: document.getElementById('productDescription').value,
            detail: document.getElementById('productDetail').value,
            status: document.getElementById('productStatus').value,
            sales: document.getElementById('productSales').value,
            remark: document.getElementById('productRemark').value
        };

        // 将商品信息添加到FormData
        formData.append('productInfo', new Blob([JSON.stringify(productInfo)], {
            type: 'application/json'
        }));

        // 添加图片文件
        const imageFiles = document.getElementById('productImages').files;
        if (imageFiles.length > 0) {
            for (let i = 0; i < imageFiles.length; i++) {
                formData.append('images', imageFiles[i]);
            }
        }

        // 添加视频文件
        const videoFiles = document.getElementById('productVideos').files;
        if (videoFiles.length > 0) {
            for (let i = 0; i < videoFiles.length; i++) {
                formData.append('videos', videoFiles[i]);
            }
        }

        fetch('http://localhost:80/admin/product/insert', {
            method: 'POST',
            headers: {
                'Authorization': currentToken
            },
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('商品添加成功！');
                    // 关闭模态框并重置表单
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addProductModal'));
                    if (modal) {
                        modal.hide();
                    }
                    document.getElementById('addProductForm').reset();
                    loadProducts(currentPage);
                } else {
                    showToast('添加失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('添加商品时发生错误', 'danger');
            });
    }

    // 处理更新销量
    function handleUpdateSales() {
        const createTime = document.getElementById('updateSalesCreateTime').value;
        const sales = document.getElementById('newSales').value;

        fetch('http://localhost:80/admin/product/updateSales', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': currentToken
            },
            body: JSON.stringify({
                createTime: createTime,
                sales: sales
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('销量更新成功！');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('updateSalesModal'));
                    if (modal) {
                        modal.hide();
                    }
                    loadProducts(currentPage);
                } else {
                    showToast('更新失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('更新销量时发生错误', 'danger');
            });
    }

    // 处理添加图片
    function handleAddImage() {
        const createTime = document.getElementById('addImageCreateTime').value;
        const imageFile = document.getElementById('newImage').files[0];

        if (!imageFile) {
            showToast('请选择图片文件', 'warning');
            return;
        }

        const formData = new FormData();
        formData.append('images', imageFile);
        formData.append('createTime', createTime);

        fetch('http://localhost:80/admin/product/addImage', {
            method: 'POST',
            headers: {
                'Authorization': currentToken
            },
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('图片添加成功！');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addImageModal'));
                    if (modal) {
                        modal.hide();
                    }
                    loadProducts(currentPage);
                } else {
                    showToast('添加失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('添加图片时发生错误', 'danger');
            });
    }

    // 处理添加视频
    function handleAddVideo() {
        const createTime = document.getElementById('addVideoCreateTime').value;
        const videoFile = document.getElementById('newVideo').files[0];

        if (!videoFile) {
            showToast('请选择视频文件', 'warning');
            return;
        }

        const formData = new FormData();
        formData.append('video', videoFile);
        formData.append('createTime', createTime);

        fetch('http://localhost:80/admin/product/addVideo', {
            method: 'POST',
            headers: {
                'Authorization': currentToken
            },
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('视频添加成功！');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addVideoModal'));
                    if (modal) {
                        modal.hide();
                    }
                    loadProducts(currentPage);
                } else {
                    showToast('添加失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('添加视频时发生错误', 'danger');
            });
    }

    // 处理删除商品
    function handleDeleteProduct() {
        const createTime = document.getElementById('deleteProductCreateTime').value;

        fetch('http://localhost:80/admin/product/delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': currentToken
            },
            body: JSON.stringify({
                createTime: createTime
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('商品删除成功！');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
                    if (modal) {
                        modal.hide();
                    }
                    loadProducts(currentPage);
                } else {
                    showToast('删除失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('删除商品时发生错误', 'danger');
            });
    }

    // 显示更新销量模态框
    function showUpdateSalesModal(createTime, currentSales) {
        document.getElementById('updateSalesCreateTime').value = createTime;
        document.getElementById('newSales').value = currentSales;
        const modalElement = document.getElementById('updateSalesModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.show();
        } else {
            // 如果实例不存在，使用Bootstrap的默认行为
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        }
    }

    // 显示添加图片模态框
    function showAddImageModal(createTime) {
        document.getElementById('addImageCreateTime').value = createTime;
        document.getElementById('newImage').value = '';
        const modalElement = document.getElementById('addImageModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.show();
        } else {
            // 如果实例不存在，使用Bootstrap的默认行为
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        }
    }

    // 显示添加视频模态框
    function showAddVideoModal(createTime) {
        document.getElementById('addVideoCreateTime').value = createTime;
        document.getElementById('newVideo').value = '';
        const modalElement = document.getElementById('addVideoModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.show();
        } else {
            // 如果实例不存在，使用Bootstrap的默认行为
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        }
    }

    // 显示删除确认模态框
    function showDeleteConfirmModal(createTime) {
        document.getElementById('deleteProductCreateTime').value = createTime;
        const modalElement = document.getElementById('deleteConfirmModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.show();
        } else {
            // 如果实例不存在，使用Bootstrap的默认行为
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        }
    }

    // 生成统计
    function generateStatistics() {
        const startDate = document.getElementById('statStartDate').value;
        const endDate = document.getElementById('statEndDate').value;

        if (!startDate || !endDate) {
            showToast('请选择完整的日期范围', 'warning');
            return;
        }

        const startTime = new Date(startDate).getTime();
        const endTime = new Date(endDate).getTime();

        if (startTime > endTime) {
            showToast('开始时间不能晚于结束时间', 'warning');
            return;
        }

        fetch('http://localhost:80/admin/product/stat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': currentToken
            },
            body: JSON.stringify({
                startTime: startTime,
                endTime: endTime
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    renderStatistics(data.data);
                } else {
                    showToast('生成统计失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('生成统计时发生错误', 'danger');
            });
    }

    // 渲染统计结果
    function renderStatistics(data) {
        const resultDiv = document.getElementById('statResult');

        if (!data || !Array.isArray(data) || data.length === 0) {
            resultDiv.innerHTML = '<p class="text-center text-muted">暂无统计数据</p>';
            return;
        }

        // 创建表格来显示商品销售数据
        let tableHtml = `
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>排名</th>
                                <th>商品名称</th>
                                <th>单价</th>
                                <th>销量</th>
                                <th>销售金额</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

        // 遍历数据并添加到表格中
        data.forEach((item, index) => {
            tableHtml += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${item.name || '未知商品'}</td>
                        <td>¥${item.price || 0}</td>
                        <td>${item.sales || 0}</td>
                        <td>¥${item.amount || 0}</td>
                    </tr>
                `;
        });

        tableHtml += `
                        </tbody>
                    </table>
                </div>
            `;

        resultDiv.innerHTML = tableHtml;
    }

    // 添加优惠券处理
    function handleAddCoupon() {
        const discount = document.getElementById('couponDiscount').value;
        const reprice = document.getElementById('couponReprice').value;
        const min = document.getElementById('couponMin').value;
        const quantity = document.getElementById('couponQuantity').value;
        const expireTime = document.getElementById('couponExpireTime').value;

        // 验证必填字段
        if (!quantity || quantity <= 0) {
            showToast('请填写有效的优惠券数量', 'warning');
            return;
        }

        if (!expireTime) {
            showToast('请选择过期时间', 'warning');
            return;
        }

        // 验证折扣率和优惠金额只能填写一个
        if ((discount && reprice) || (!discount && !reprice)) {
            showToast('折扣率和优惠金额只能填写一个，另一个必须为空', 'warning');
            return;
        }

        // 构造优惠券对象
        const coupon = {
            discount: discount ? parseFloat(discount) : 0,
            reprice: reprice ? parseFloat(reprice) : 0,
            min: min ? parseFloat(min) : 0,
            quantity: parseInt(quantity),
            expireTime: new Date(expireTime).getTime()
        };

        // 发送请求
        fetch('http://localhost:80/admin/coupon/insert', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': currentToken
            },
            body: JSON.stringify(coupon)
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('优惠券添加成功！');
                    // 关闭模态框并重置表单
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addCouponModal'));
                    if (modal) {
                        modal.hide();
                    }
                    document.getElementById('addCouponForm').reset();
                    loadCoupons();
                } else {
                    showToast('添加失败：' + data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('添加优惠券时发生错误', 'danger');
            });
    }
</script>
</body>
</html>